<template>
  <div class="list">
    <van-nav-bar left-arrow @click-left="onClickLeft" />
    <div class="home-goods">
      <!-- 循环渲染GoodsItem -->
      <template v-for="(item, key) in goodsList">
        <ListItem :goods="item" class="item" />
      </template>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { getGoods, getHotAndNewGoodsList } from '@/api/modules/goods'
import { useRoute } from 'vue-router'
import ListItem from './ListItem.vue'
const route = useRoute()

const goodsList = ref([])

const getGoodsList = async ({ id, type }) => {
  // 如果有id则表示从分类页面跳转过来的
  if (id) {
    const {
      data: { data }
    } = await getGoods({ category: id })
    goodsList.value = data.list
  } else if (type) {
    if (type === 'hot') {
      const {
        data: { data }
      } = await getHotAndNewGoodsList({ isHot: 1 })
      goodsList.value = data
      return
    }
    if (type) {
      const {
        data: { data }
      } = await getHotAndNewGoodsList({ isNew: 1 })
      goodsList.value = data
      return
    }
  }
}

const onClickLeft = () => history.back()

// ===生命周期钩子===

onMounted(() => {
  console.log('List页面挂载')
  const { id, type } = route.query
  if (id) {
    getGoodsList({ id })
  } else {
    if (type === 'hot') {
      getGoodsList({ type: 'hot' })
    } else {
      getGoodsList({ type: 'new' })
    }
  }
})
</script>

<style lang="less" scoped>
.list {
  background-color: #f5f5f5;
  min-height: 100vh;
}
.home-goods {
  display: flex;
  flex-wrap: wrap;
  background-color: #f5f5f5;
  justify-content: space-around;
  padding: 10px;

  .item {
    width: 45%;
    margin-bottom: 10px;
  }
  .item:last-child {
    margin-right: auto;
    margin-left: 9px;
  }
}
/deep/ .van-nav-bar .van-icon {
  color: #1ba784 !important;
}
</style>
